package org.abettor.pushbox.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import org.abettor.android.ads.YoumiManager;
import org.abettor.pushbox.activity2.ShowAnswerMapDetailActivity;
import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.download.DownloadMap;
import org.abettor.pushbox.download.ParaDownloadRetValue;
import org.abettor.pushbox.map.AsyncGenerateNetMapThumbImage;
import org.abettor.pushbox.model.NetPushBoxMapBean;
import org.abettor.pushbox.model.NotifyBean;
import org.abettor.pushbox.model.SelfMessage;
import org.abettor.pushbox.R;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.TabHost.OnTabChangeListener;

public class QuesstionMapActivity extends TabActivity {
	private static final int VIEW_ANSWER = Menu.FIRST;// 查看答案
	private static final int PUSH_MAP = Menu.FIRST + 1;// 解答答案
	private static final int VIEW_DETAIL = Menu.FIRST + 2;//
	private final float WIDTH = 70, HEIGHT = 70;
	private DownloadMap netBeanDown = null;// 用来下载地图的bean
	private TabHost tabHost = null;// 标签的host
	private static final String TAB1 = "tab1", TAB2 = "tab2";
	private String curTab = null;// 当前的tab
	private boolean isLoading = false;// 判断当前的状态，是否处于加载状态
	private MyOnTabChangeListener tabListener = new MyOnTabChangeListener();
	private TabHost.TabSpec questionSpec;// 用户列表的标签
	private TabHost.TabSpec myloadedSpec;// 我上传地图的标签
	private ListView quesstionListView;// 显示列表的控件
	private ListView myQuesstionListView;// 我上传列表的控件
	private ProgressBar progressBar, progressBar1;// 进度条
	private MyQuesstionListAdapter myListAdapter;// 图的列表
	private QuesstionListAdapter qListAdapter;// 难图的列表
	private Handler mHandler = new Handler();
	private int isHasMore;// 判断是否还有更多的数据
	private MyQuesstionItemClickListenner myQuesstionItemListenner = new MyQuesstionItemClickListenner();
	private QuesstionItemClickListenner quesstionItemListenner = new QuesstionItemClickListenner();
	/*-----------------------广告-------------------*/
	private final int SHOW_AD = 13579;
	private YoumiManager youmi = new YoumiManager(this);
	private Handler youmiHandle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == SHOW_AD) {
				// 按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if (val < 70) {
					youmi.showYoumi(YoumiManager.Position.bottom, Color.WHITE,
							Color.BLACK, 0xAA);
				}
			}

			super.handleMessage(msg);
		}
	};
	private Thread youmiDelayThread = new Thread() {
		@Override
		public void run() {
			try {
				Thread.sleep(200);
				Message msg = new Message();
				msg.what = SHOW_AD;
				youmiHandle.sendMessage(msg);
			} catch (InterruptedException e) {
				Log.d(this.getClass().getName(), "", e);
			}
		}
	};

	/*--------------------------------注册Context menu------------------------------------------------------*/
	/**
	 * 注册context 菜单
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		// if (v == quesstionListView) {// 我的菜单
		// AdapterView.AdapterContextMenuInfo info =
		// (AdapterView.AdapterContextMenuInfo) menuInfo;
		menu.setHeaderTitle(R.string.quesstion_map);
		menu.add(0, VIEW_ANSWER, 0, R.string.view_net_map_answer);
		menu.add(0, PUSH_MAP, 1, R.string.net_map_do_answer);
		menu.add(0, VIEW_DETAIL, 2, R.string.net_map_view_detail);
		// } else {
		// }
	}

	@Override
	public boolean onContextItemSelected(MenuItem aItem) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) aItem
				.getMenuInfo();
		switch (aItem.getItemId()) {
		case VIEW_ANSWER:
			Intent in = new Intent();
			Bundle extras = new Bundle();
			extras.putInt("_id", (int) info.id);
			in.putExtras(extras);
			in.setClass(QuesstionMapActivity.this,
					QuesstionAnswerListActivity.class);
			startActivity(in);
			break;
		case PUSH_MAP:
			doAnswer(info.targetView,(int)info.id);
			break;
		case VIEW_DETAIL:
			doViewDetail((int)info.id);
			break;
		}
		return false;
	}

	/*-------------------------- onclickitem ------------------------------------*/
	private class MyQuesstionItemClickListenner implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> l, View v, int position, long id) {
			doViewDetail((int) id);
		}
	}

	// 查看地图的详情
	private void doViewDetail(int id) {
		Intent in = new Intent();
		Bundle extras = new Bundle();
		extras.putInt("_id", id);
		in.putExtras(extras);
		in.setClass(this, ShowAnswerMapDetailActivity.class);
		startActivity(in);
	}

	private class QuesstionItemClickListenner implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> l, View v, int position, long id) {
			doViewDetail((int) id);
		}
	}

	private void doAnswer(View v, int id) {
		Intent in = new Intent();
		Bundle extras = new Bundle();
		extras.putInt("_id", (int) id);
		in.putExtras(extras);
		TextView hidden = (TextView) v.findViewWithTag("hidden");
		String text = hidden.getText().toString();
		if ("1".equals(text)) {// 判断是否本人已经解决
			// 本人已解决，先查寻本地答案文件是否已经存在,不存在的话，打开地图的文件，存在的话打开解答后的地图
			String filePath = Config.getNetBasePath() + File.separator
					+ String.valueOf(id) + ".step";
			File file = new File(filePath);
			if (!file.exists()) {
				in.setClass(QuesstionMapActivity.this,
						QuesstionPushBoxActivity.class);
			} else {
				in.setClass(QuesstionMapActivity.this,
						QuesstionBoxShowResultActivity.class);
			}
		} else {// 本人未解决的条件
			in.setClass(QuesstionMapActivity.this,
					QuesstionPushBoxActivity.class);
		}
		startActivity(in);
	}

	/*--------------------------------------------------------------------------*/
	// 更新消息的操作
	private void alertMsg() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog dialog = builder.create();
		dialog.setTitle(R.string.msg);
		dialog.setMessage(this.getText(R.string.input_nickname_first));
		// 拦截back key
		dialog.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					Intent in = new Intent();
					in.setClass(QuesstionMapActivity.this, OptionActivity.class);
					startActivity(in);
					QuesstionMapActivity.this.finish();
					return true;
				}
				return false;
			}
		});
		dialog.setButton(DialogInterface.BUTTON_POSITIVE,
				this.getText(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent in = new Intent();
						in.setClass(QuesstionMapActivity.this,
								OptionActivity.class);
						startActivity(in);
						QuesstionMapActivity.this.finish();
					}
				});
		dialog.show();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 进行检查昵称是否配置了的操作
		SelfMessage self = Config.readSelfMessage(this);
		if (self == null) {
			alertMsg();
			return;
		}
		super.setContentView(R.layout.net_user_map_activity);
		myListAdapter = new MyQuesstionListAdapter(
				new LinkedList<NetPushBoxMapBean>());
		qListAdapter = new QuesstionListAdapter(
				new LinkedList<NetPushBoxMapBean>());
		netBeanDown = new DownloadMap(this);
		tabHost = getTabHost();
		tabHost.setOnTabChangedListener(tabListener);
		LayoutInflater.from(this).inflate(R.layout.quesstion_map_tabhost,
				tabHost.getTabContentView(), true);
		questionSpec = tabHost.newTabSpec(TAB1);
		myloadedSpec = tabHost.newTabSpec(TAB2);
		setIndicator(questionSpec, R.string.quesstion_map_maplist);
		setIndicator(myloadedSpec, R.string.quesstion_map_mymaplist);
		questionSpec.setContent(R.id.view1);
		myloadedSpec.setContent(R.id.view2);
		tabHost.addTab(questionSpec);
		tabHost.addTab(myloadedSpec);
		curTab = TAB1;
		// 获得list的列表
		quesstionListView = (ListView) this.findViewById(R.id.questionMapList);
		myQuesstionListView = (ListView) this.findViewById(R.id.myQuestionList);
		addFooterView(quesstionListView);
		addFooterView(myQuesstionListView);
		quesstionListView.setAdapter(qListAdapter);
		quesstionListView.setOnItemClickListener(quesstionItemListenner);
		myQuesstionListView.setAdapter(myListAdapter);
		myQuesstionListView.setOnItemClickListener(myQuesstionItemListenner);
		// 加入滚动的监听器
		quesstionListView.setOnScrollListener(new QuesstionScrollAdapter());
		myQuesstionListView.setOnScrollListener(new MyQuesstionScrollAdapter());
		// 加入context的监听器
		this.registerForContextMenu(quesstionListView);
		this.registerForContextMenu(myQuesstionListView);
		youmiDelayThread.start();
	}

	// 增加footer view
	private void addFooterView(ListView listView) {
		View localView = LayoutInflater.from(this).inflate(
				R.layout.net_user_map_list_footer, null);
		listView.addFooterView(localView);
	}

	// 设置文字的颜色
	private void setIndicator(TabHost.TabSpec spec, int title) {
		View localView = LayoutInflater.from(this).inflate(
				R.layout.net_user_map_tab, null);
		TextView localTextView = (TextView) localView
				.findViewById(R.id.net_user_tab_text);
		localTextView.setText(title);
		spec.setIndicator(localView);
	}

	// 加载我上传的地图列表
	private void loadMyQuestionMap(final String nickName) {
		if (isLoading) {
			return;
		}
		Thread thread = new Thread() {
			@Override
			public void run() {
				loadMyQuestionMapOperation(nickName);
			}
		};
		curTab = TAB2;
		isLoading = true;// 把状态设为加载中
		showProgressBar1();// 显示加载中的progressbar
		thread.start();
	}

	// 加载疑难的列表
	private void loadQuestionMap() {
		// 已经加载时将不在加载数据
		if (isLoading) {
			return;
		}
		Thread thread = new Thread() {
			@Override
			public void run() {
				loadQuestionMapOperation();
			}
		};
		curTab = TAB1;
		isLoading = true;// 把状态设为加载中
		showProgressBar();// 显示加载中的progressbar
		thread.start();
	}

	private void loadMyQuestionMapOperation(final String nickName) {
		SelfMessage self = Config.readSelfMessage(QuesstionMapActivity.this);
		String mySelfName = null;
		if (self != null) {
			mySelfName = self.getNickName();
		}
		Date lastAccessTime = null;// 用来存取最后一条记录的基准时间
		lastAccessTime = myListAdapter.getLastAccessTime();
		String content = netBeanDown.downloadQuesstionMapListStr(nickName,
				lastAccessTime, mySelfName, Config.PAGESIZE);
		dispearProgressBar1();
		isLoading = false;
		// 读取内容为空，显示加载失败的对话框
		if (content == null) {
			loadMyNetQuesstionMapFailure(nickName);// 显示加载失败的对话框
			return;
		}
		// 判断是否还有多余的数据
		isHasMore = ParaDownloadRetValue.isHasMoreNetMap(content);
		// 解析数据内容失败，显示加载失败的对话框
		if (isHasMore == ParaDownloadRetValue.ERROR) {
			loadMyNetQuesstionMapFailure(nickName);// 显示加载失败的对话框
			return;
		}
		// 解析数据的列表
		final List<NetPushBoxMapBean> retList = ParaDownloadRetValue
				.paraNetMap(content);
		if (retList == null) {
			loadMyNetQuesstionMapFailure(nickName);// 显示加载失败的对话框
			return;
		}
		// 显示加载后的列表框
		showMyQuestionMapView();
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				myListAdapter.addNetPushBoxMapBean(retList);
				myListAdapter.notifyDataSetChanged();
			}
		});
	}

	private void loadQuestionMapOperation() {
		SelfMessage self = Config.readSelfMessage(QuesstionMapActivity.this);
		String mySelfName = null;
		if (self != null) {
			mySelfName = self.getNickName();
		}
		Date lastAccessTime = null;// 用来存取最后一条记录的基准时间
		lastAccessTime = qListAdapter.getLastAccessTime();
		String content = netBeanDown.downloadQuesstionMapListStr(null,
				lastAccessTime, mySelfName, Config.PAGESIZE);
		Log.d(this.getClass().getName(), content != null ? content : "");
		dispearProgressBar();
		isLoading = false;
		// 读取内容为空，显示加载失败的对话框
		if (content == null) {
			loadNetQuesstionMapFailure();// 显示加载失败的对话框
			return;
		}
		// 判断是否还有多余的数据
		isHasMore = ParaDownloadRetValue.isHasMoreNetMap(content);
		// 解析数据内容失败，显示加载失败的对话框
		if (isHasMore == ParaDownloadRetValue.ERROR) {
			loadNetQuesstionMapFailure();// 显示加载失败的对话框
			return;
		}
		// 解析数据的列表
		final List<NetPushBoxMapBean> retList = ParaDownloadRetValue
				.paraNetMap(content);
		if (retList == null) {
			loadNetQuesstionMapFailure();// 显示加载失败的对话框
			return;
		}
		// 显示加载后的列表框
		showQuestionMapView();
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				qListAdapter.addNetPushBoxMapBean(retList);
				qListAdapter.notifyDataSetChanged();
			}
		});
	}

	// show List View
	private void showQuestionMapView() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if (quesstionListView.getVisibility() == View.GONE) {
					quesstionListView.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	private void showMyQuestionMapView() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if (myQuesstionListView.getVisibility() == View.GONE) {
					myQuesstionListView.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	// 显示加载网络地图错误的的对话狂
	private void loadNetQuesstionMapFailure() {
		mHandler.post(new LoadFailureRunnable() {
			@Override
			public void loadMap() {
				loadQuestionMap();
			}
		});
	}

	private void loadMyNetQuesstionMapFailure(final String nickName) {
		mHandler.post(new LoadFailureRunnable() {
			@Override
			public void loadMap() {
				loadMyQuestionMapOperation(nickName);
			}
		});
	}

	private void dispearProgressBar1() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				int state = myQuesstionListView.getVisibility();
				if (state == View.GONE) {// 大对话框，消失的操作
					progressBar = (ProgressBar) QuesstionMapActivity.this
							.findViewById(R.id.progressBar2);
					progressBar.setVisibility(View.GONE);
				} else {// 小对话框的消失操作
					View view = quesstionListView.findViewById(R.id.footor);
					view.setVisibility(View.GONE);
				}
			}
		});
	}

	// dispear progressBar
	private void dispearProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				int state = quesstionListView.getVisibility();
				if (state == View.GONE) {// 大对话框，消失的操作
					progressBar = (ProgressBar) QuesstionMapActivity.this
							.findViewById(R.id.progressBar1);
					progressBar.setVisibility(View.GONE);
				} else {// 小对话框的消失操作
					View view = quesstionListView.findViewById(R.id.footor);
					view.setVisibility(View.GONE);
				}
			}
		});
	}

	// show progressBar
	private void showProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				// 当列表框还没显示时显示大的加载框，当显示时显示列表中小的对话框
				int state = quesstionListView.getVisibility();
				if (state == View.GONE) {
					progressBar = (ProgressBar) QuesstionMapActivity.this
							.findViewById(R.id.progressBar1);
					progressBar.setVisibility(View.VISIBLE);
				} else {
					View view = quesstionListView.findViewById(R.id.footor);
					view.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	private void showProgressBar1() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				// 当列表框还没显示时显示大的加载框，当显示时显示列表中小的对话框
				int state = myQuesstionListView.getVisibility();
				if (state == View.GONE) {
					progressBar1 = (ProgressBar) QuesstionMapActivity.this
							.findViewById(R.id.progressBar2);
					progressBar1.setVisibility(View.VISIBLE);
				} else {
					View view = myQuesstionListView.findViewById(R.id.footor);
					view.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	/*---------------------------- 滚动条的adapter ---------------------------------*/
	private abstract class MyOnScrollListener implements OnScrollListener {
		private boolean linloading = false;
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// 把totalItemCount剔除掉，因为加入footer，所以剔除掉totalItemCount为1的时候
			if (totalItemCount == 1) {
				return;
			}
			if (firstVisibleItem + visibleItemCount >= totalItemCount
					&& isHasMore == ParaDownloadRetValue.HASMORE) {
				if (!linloading) {
					linloading = true;
					loadMap();// 加载数据
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							linloading = false;
						}
					}, 4000);
				}
				//loadMap();// 加载数据
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}

		protected abstract void loadMap();//
	}

	// quesstion 滚动的监听器
	private class QuesstionScrollAdapter extends MyOnScrollListener {
		@Override
		protected void loadMap() {
			loadQuestionMap();
		}
	}

	// my quesstion 滚动的监听器
	private class MyQuesstionScrollAdapter extends MyOnScrollListener {
		@Override
		protected void loadMap() {
			SelfMessage self = Config
					.readSelfMessage(QuesstionMapActivity.this);
			if (self != null) {
				loadMyQuestionMap(self.getNickName());
			}
		}
	}

	/*--------------------------- 滚动条的adapter end ------------------------------*/

	/*---------------------- list adapter -------------------------------------*/
	private class MyQuesstionListAdapter extends UserMapAdapter {
		public MyQuesstionListAdapter(List<NetPushBoxMapBean> list) {
			super(list);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			final NetPushBoxMapBean item;
			synchronized (netBeanList) {
				item = netBeanList.get(position);
			}
			LayoutInflater inflater = QuesstionMapActivity.this
					.getLayoutInflater();
			ViewGroup theParent = (ViewGroup) inflater.inflate(
					R.layout.quesstion_user_map_list_item, parent, false);
			TextView createTimeView = (TextView) theParent
					.findViewWithTag("createTime");
			TextView messageView = (TextView) theParent
					.findViewWithTag("message");
			TextView hidden = (TextView) theParent.findViewWithTag("hidden");
			TextView resovledCount = (TextView) theParent
					.findViewWithTag("resolveCount");
			final ImageView thumbImageView = (ImageView) theParent
					.findViewWithTag("thumbImage");
			if (item.getBitmap() != null) {
				thumbImageView.setImageBitmap(item.getBitmap());
			} else {// 图片为null的话，异步更新图片
				// 设置异步更新的图片的操作
				AsyncGenerateNetMapThumbImage.NetImageCallBack callBack = new AsyncGenerateNetMapThumbImage.NetImageCallBack() {
					@Override
					public void processImage(Bitmap bit) {
						if (bit != null) {
							thumbImageView.setImageBitmap(bit);
							item.setBitmap(bit);
						}
					}
				};
				AsyncGenerateNetMapThumbImage asyn = new AsyncGenerateNetMapThumbImage(
						WIDTH, HEIGHT, callBack, QuesstionMapActivity.this) {
					@Override
					public int getNetMapId() {
						return item.getId();
					}

					@Override
					public String getMapFilePath() {
						return Config.getNetBasePath();
					}

					@Override
					public String getThumbNailPath() {
						return Config.getNetBasePath();
					}
				};
				asyn.start();
			}
			// 设置时间
			createTimeView.setText(QuesstionMapActivity.this
					.getText(R.string.map_create_time)
					+ "\n"
					+ sdf.format(item.getUploadDate()));
			messageView.setText(changeMsgToStr(item));
			// 设置是否已经解决
			if (item.isMyresolved()) {
				hidden.setText("1");
			} else {
				hidden.setText("0");
			}
			resovledCount.setText(item.getResolvedCount());
			return theParent;
		}

		// 把消息转换为字符串
		private String changeMsgToStr(NetPushBoxMapBean bean) {
			String ret = "";
			ret = ret
					+ QuesstionMapActivity.this
							.getText(R.string.netuser_map_upor) + ":"
					+ bean.getUploader() + "\n";
			if (bean.isMyresolved()) {
				ret += QuesstionMapActivity.this
						.getText(R.string.netuser_map_resolved);
			} else {
				ret += QuesstionMapActivity.this
						.getText(R.string.netuser_map_unresolved);
			}
			ret += "(";
			ret += QuesstionMapActivity.this
					.getText(R.string.netuser_map_total);
			ret += bean.getResolvedCount()
					+ QuesstionMapActivity.this
							.getText(R.string.netuser_map_has_resolved) + ")";
			return ret;
		}
	}

	private class QuesstionListAdapter extends UserMapAdapter {
		public QuesstionListAdapter(List<NetPushBoxMapBean> list) {
			super(list);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			final NetPushBoxMapBean item;
			synchronized (netBeanList) {
				item = netBeanList.get(position);
			}
			LayoutInflater inflater = QuesstionMapActivity.this
					.getLayoutInflater();
			ViewGroup theParent = (ViewGroup) inflater.inflate(
					R.layout.my_quesstion_user_map_list_item, parent, false);
			TextView createTimeView = (TextView) theParent
					.findViewWithTag("createTime");
			TextView messageView = (TextView) theParent
					.findViewWithTag("message");
			TextView hidden = (TextView) theParent.findViewWithTag("hidden");
			TextView resovledCount = (TextView) theParent
					.findViewWithTag("resolveCount");
			final ImageView thumbImageView = (ImageView) theParent
					.findViewWithTag("thumbImage");
			if (item.getBitmap() != null) {
				thumbImageView.setImageBitmap(item.getBitmap());
			} else {// 图片为null的话，异步更新图片
				// 设置异步更新的图片的操作
				AsyncGenerateNetMapThumbImage.NetImageCallBack callBack = new AsyncGenerateNetMapThumbImage.NetImageCallBack() {
					@Override
					public void processImage(Bitmap bit) {
						if (bit != null) {
							thumbImageView.setImageBitmap(bit);
							item.setBitmap(bit);
						}
					}
				};
				AsyncGenerateNetMapThumbImage asyn = new AsyncGenerateNetMapThumbImage(
						WIDTH, HEIGHT, callBack, QuesstionMapActivity.this) {
					@Override
					public int getNetMapId() {
						return item.getId();
					}

					@Override
					public String getMapFilePath() {
						return Config.getNetBasePath();
					}

					@Override
					public String getThumbNailPath() {
						return Config.getNetBasePath();
					}
				};
				asyn.start();
			}
			// 设置时间
			createTimeView.setText(QuesstionMapActivity.this
					.getText(R.string.map_create_time)
					+ "\n"
					+ sdf.format(item.getUploadDate()));
			messageView.setText(changeMsgToStr(item));
			// 设置是否已经解决
			if (item.isMyresolved()) {
				hidden.setText("1");
			} else {
				hidden.setText("0");
			}
			resovledCount.setText(item.getResolvedCount());
			return theParent;
		}

		// 把消息转换为字符串
		private String changeMsgToStr(NetPushBoxMapBean bean) {
			String ret = "";
			ret = ret
					+ QuesstionMapActivity.this
							.getText(R.string.netuser_map_upor) + ":"
					+ bean.getUploader() + "\n";
			if (bean.isMyresolved()) {
				ret += QuesstionMapActivity.this
						.getText(R.string.netuser_map_resolved);
			} else {
				ret += QuesstionMapActivity.this
						.getText(R.string.netuser_map_unresolved);
			}
			ret += "(";
			ret += QuesstionMapActivity.this
					.getText(R.string.netuser_map_total);
			ret += bean.getResolvedCount()
					+ QuesstionMapActivity.this
							.getText(R.string.netuser_map_has_resolved) + ")";
			return ret;
		}
	}

	// 通用的类
	private abstract class UserMapAdapter extends BaseAdapter {
		protected List<NetPushBoxMapBean> netBeanList;

		public void clear() {
			synchronized (netBeanList) {
				netBeanList.clear();
			}
		}

		// 获得最后一次更新时间
		public Date getLastAccessTime() {
			if (netBeanList == null || netBeanList.isEmpty()) {
				return null;
			}
			int size = netBeanList.size();
			NetPushBoxMapBean bean = null;
			synchronized (netBeanList) {
				bean = netBeanList.get(size - 1);
			}
			return bean.getUploadDate();
		}

		/**
		 * 向列表中加入数据
		 * 
		 * @param toAdd
		 */
		public void addNetPushBoxMapBean(List<NetPushBoxMapBean> toAdd) {
			if (toAdd == null) {
				return;
			}
			Date lastTime = getLastAccessTime();
			if(lastTime != null){
			}
			Iterator<NetPushBoxMapBean> itr = toAdd.iterator();
			while (itr.hasNext()) {
				NetPushBoxMapBean n = itr.next();
				if (lastTime == null || n.getUploadDate().before(lastTime)) {
					netBeanList.add(n);
				} else {
					netBeanList.add(0, n);
				}
			}
		}

		/**
		 * 构造方法
		 * 
		 * @param list
		 */
		public UserMapAdapter(List<NetPushBoxMapBean> list) {
			this.netBeanList = list;
		}

		@Override
		public int getCount() {
			synchronized (netBeanList) {
				return netBeanList.size();
			}
		}

		@Override
		public Object getItem(int position) {
			synchronized (netBeanList) {
				return netBeanList.get(position);
			}
		}

		@Override
		public long getItemId(int position) {
			synchronized (netBeanList) {
				return netBeanList.get(position).getId();
			}
		}
	}

	/*------------------------- list adapter end -------------------------------*/
	private void resetQuesstionListView() {
		quesstionListView.setVisibility(View.GONE);
		qListAdapter.clear();
	}

	private void resetMyQuesstionListView() {
		myQuesstionListView.setVisibility(View.GONE);
		myListAdapter.clear();
	}

	@Override
	public void onStart() {
		super.onStart();
		int notifyId = getIntent().getIntExtra(NotifyBean.NOTIFY_TAG, -1);
		if(notifyId >= 0)
		{
			NotificationManager notiMgmt = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			notiMgmt.cancel(NotifyBean.NOTIFY_TAG, notifyId);
		}

		SelfMessage self = Config.readSelfMessage(this);
		if (self == null) {
			alertMsg();
			return;
		}
		if (curTab.equals(TAB1)) {
			if (isLoading) {
				return;
			}
			resetQuesstionListView();
			loadQuestionMap();
		} else if (curTab.equals(TAB2)) {
			if (isLoading) {
				return;
			}
			resetMyQuesstionListView();
			loadMyQuestionMap(self.getNickName());
		}
	}

	// Tab Listener
	private class MyOnTabChangeListener implements OnTabChangeListener {
		private boolean qloded = false, myloaded = false;// 是否第一次启动

		@Override
		public void onTabChanged(String tabId) {
			// 正在加载时，不允许切换到别的tag
			if (isLoading) {
				tabHost.setCurrentTabByTag(curTab);
				return;
			} else {
				curTab = tabId;
			}
			if (TAB1.equals(tabId)) {
				if (!qloded) {
					loadQuestionMap();
					qloded = true;
				}
			} else if (TAB2.equals(tabId)) {
				SelfMessage self = Config
						.readSelfMessage(QuesstionMapActivity.this);
				if (self == null) {
					doUnreg();
					return;
				} else {
					if (!myloaded) {
						loadMyQuestionMap(self.getNickName());
						myloaded = true;
					}
				}
			}
		}
	}

	// 进行没有输入用户名的操作
	private void doUnreg() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog alert = builder.create();
		alert.setTitle(R.string.info);
		alert.setMessage(QuesstionMapActivity.this
				.getText(R.string.netuser_map_unreginfo));
		alert.setButton(DialogInterface.BUTTON_POSITIVE,
				this.getText(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent();
						intent.setClass(QuesstionMapActivity.this,
								OptionActivity.class);
						QuesstionMapActivity.this.startActivity(intent);
					}
				});
		alert.setButton(DialogInterface.BUTTON_NEGATIVE,
				this.getText(android.R.string.cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		alert.show();
	}

	/**
	 * 进行加载失败处理的类
	 * 
	 * @author jzh
	 * 
	 */
	private abstract class LoadFailureRunnable implements Runnable {
		@Override
		public void run() {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					QuesstionMapActivity.this);
			AlertDialog alert = builder.create();
			alert.setTitle(R.string.error);
			alert.setMessage(QuesstionMapActivity.this
					.getText(R.string.netuser_loadmap_failure));
			alert.setButton(DialogInterface.BUTTON_POSITIVE,
					QuesstionMapActivity.this.getText(R.string.netuser_retry),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 显示加载的对话标签
							showProgressBar();
							// 重新网络地图的操作
							loadMap();
						}
					});
			alert.setButton(DialogInterface.BUTTON_NEGATIVE,
					QuesstionMapActivity.this.getText(android.R.string.cancel),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			alert.show();
		}

		public abstract void loadMap();
	}
}
